package algorithms

import (
	"log"
	"math"
	"sort"
	"strings"

	"navigation-service/internal/models"
)

// PatternAnalyzer 模式分析器
type PatternAnalyzer struct {
	features []models.URLFeature
}

// NewPatternAnalyzer 创建模式分析器
func NewPatternAnalyzer(features []models.URLFeature) *PatternAnalyzer {
	return &PatternAnalyzer{
		features: features,
	}
}

// AnalyzeAllPatterns 分析所有模式
func (pa *PatternAnalyzer) AnalyzeAllPatterns() map[string]interface{} {
	log.Printf("=== 开始全面模式分析 ===")
	log.Printf("分析特征数量: %d", len(pa.features))

	result := make(map[string]interface{})

	// 1. 基本统计模式
	result["basic_stats"] = pa.analyzeBasicStats()

	// 2. 访问频率模式
	result["frequency_patterns"] = pa.analyzeFrequencyPatterns()

	// 3. 时间访问模式
	result["time_patterns"] = pa.analyzeTimePatterns()

	// 4. 域名分布模式
	result["domain_patterns"] = pa.analyzeDomainPatterns()

	// 5. 内容分类模式
	result["content_patterns"] = pa.analyzeContentPatterns()

	// 6. 用户行为模式
	result["behavior_patterns"] = pa.analyzeBehaviorPatterns()

	// 7. 兴趣偏好模式
	result["interest_patterns"] = pa.analyzeInterestPatterns()

	log.Printf("=== 模式分析完成 ===")
	return result
}

// analyzeBasicStats 分析基本统计信息
func (pa *PatternAnalyzer) analyzeBasicStats() map[string]interface{} {
	log.Printf("分析基本统计信息")

	if len(pa.features) == 0 {
		return map[string]interface{}{
			"total_urls":     0,
			"total_visits":   0,
			"average_visits": 0.0,
		}
	}

	totalVisits := 0
	totalURLs := len(pa.features)
	urlLengths := make([]int, 0, totalURLs)
	titleLengths := make([]int, 0, totalURLs)

	for _, feature := range pa.features {
		totalVisits += feature.VisitCount
		urlLengths = append(urlLengths, len(feature.URL))
		titleLengths = append(titleLengths, len(feature.Title))
	}

	// 计算统计指标
	avgVisits := float64(totalVisits) / float64(totalURLs)
	avgURLLength := pa.calculateAverage(urlLengths)
	avgTitleLength := pa.calculateAverage(titleLengths)

	// 计算访问次数分布
	visitCounts := make([]int, 0, totalURLs)
	for _, feature := range pa.features {
		visitCounts = append(visitCounts, feature.VisitCount)
	}
	sort.Ints(visitCounts)

	medianVisits := pa.calculateMedian(visitCounts)
	p95Visits := pa.calculatePercentile(visitCounts, 95)
	p99Visits := pa.calculatePercentile(visitCounts, 99)

	stats := map[string]interface{}{
		"total_urls":           totalURLs,
		"total_visits":         totalVisits,
		"average_visits":       math.Round(avgVisits*100) / 100,
		"median_visits":        medianVisits,
		"p95_visits":           p95Visits,
		"p99_visits":           p99Visits,
		"average_url_length":   math.Round(avgURLLength*100) / 100,
		"average_title_length": math.Round(avgTitleLength*100) / 100,
	}

	log.Printf("基本统计完成: %d个URL, %d次访问, 平均%.2f次/URL",
		totalURLs, totalVisits, avgVisits)

	return stats
}

// analyzeFrequencyPatterns 分析访问频率模式
func (pa *PatternAnalyzer) analyzeFrequencyPatterns() map[string]interface{} {
	log.Printf("分析访问频率模式")

	if len(pa.features) == 0 {
		return map[string]interface{}{}
	}

	// 按访问次数排序
	sortedFeatures := make([]models.URLFeature, len(pa.features))
	copy(sortedFeatures, pa.features)
	sort.Slice(sortedFeatures, func(i, j int) bool {
		return sortedFeatures[i].VisitCount > sortedFeatures[j].VisitCount
	})

	// 计算频率分布
	totalVisits := 0
	for _, feature := range pa.features {
		totalVisits += feature.VisitCount
	}

	// 高频URL (前10%)
	highFreqCount := len(sortedFeatures) / 10
	if highFreqCount == 0 {
		highFreqCount = 1
	}
	highFreqVisits := 0
	for i := 0; i < highFreqCount; i++ {
		highFreqVisits += sortedFeatures[i].VisitCount
	}

	// 中频URL (中间80%)
	middleFreqCount := len(sortedFeatures) * 8 / 10
	middleFreqVisits := 0
	for i := highFreqCount; i < highFreqCount+middleFreqCount && i < len(sortedFeatures); i++ {
		middleFreqVisits += sortedFeatures[i].VisitCount
	}

	// 低频URL (后10%)
	lowFreqVisits := totalVisits - highFreqVisits - middleFreqVisits

	// 帕累托分析 (80/20法则)
	pareto80Count := 0
	pareto80Visits := 0
	for _, feature := range sortedFeatures {
		pareto80Visits += feature.VisitCount
		pareto80Count++
		if pareto80Visits >= totalVisits*80/100 {
			break
		}
	}

	patterns := map[string]interface{}{
		"total_visits": totalVisits,
		"frequency_distribution": map[string]interface{}{
			"high_frequency": map[string]interface{}{
				"url_count":   highFreqCount,
				"visit_count": highFreqVisits,
				"percentage":  math.Round(float64(highFreqVisits)/float64(totalVisits)*10000) / 100,
			},
			"middle_frequency": map[string]interface{}{
				"url_count":   middleFreqCount,
				"visit_count": middleFreqVisits,
				"percentage":  math.Round(float64(middleFreqVisits)/float64(totalVisits)*10000) / 100,
			},
			"low_frequency": map[string]interface{}{
				"url_count":   len(sortedFeatures) - highFreqCount - middleFreqCount,
				"visit_count": lowFreqVisits,
				"percentage":  math.Round(float64(lowFreqVisits)/float64(totalVisits)*10000) / 100,
			},
		},
		"pareto_analysis": map[string]interface{}{
			"top_urls_count":             pareto80Count,
			"top_urls_percentage":        math.Round(float64(pareto80Count)/float64(len(sortedFeatures))*10000) / 100,
			"top_urls_visits":            pareto80Visits,
			"top_urls_visits_percentage": math.Round(float64(pareto80Visits)/float64(totalVisits)*10000) / 100,
		},
		"top_10_urls": pa.getTopURLs(sortedFeatures, 10),
	}

	log.Printf("频率模式分析完成: 高频%d个URL占%.2f%%访问",
		highFreqCount, math.Round(float64(highFreqVisits)/float64(totalVisits)*10000)/100)

	return patterns
}

// analyzeTimePatterns 分析时间访问模式
func (pa *PatternAnalyzer) analyzeTimePatterns() map[string]interface{} {
	log.Printf("分析时间访问模式")

	hourlyVisits := make([]int, 24)
	totalVisits := 0

	// 统计访问时间
	for _, feature := range pa.features {
		for hour, visits := range feature.VisitPattern {
			hourlyVisits[hour] += visits
			totalVisits += visits
		}
	}

	// 找到访问高峰时段
	peakHour := 0
	maxHourlyVisits := 0
	for hour, visits := range hourlyVisits {
		if visits > maxHourlyVisits {
			maxHourlyVisits = visits
			peakHour = hour
		}
	}

	// 分析访问时段分布
	morningVisits := 0   // 6-12
	afternoonVisits := 0 // 12-18
	eveningVisits := 0   // 18-22
	nightVisits := 0     // 22-6

	for hour, visits := range hourlyVisits {
		if hour >= 6 && hour < 12 {
			morningVisits += visits
		} else if hour >= 12 && hour < 18 {
			afternoonVisits += visits
		} else if hour >= 18 && hour < 22 {
			eveningVisits += visits
		} else {
			nightVisits += visits
		}
	}

	// 计算访问模式类型
	timePatternType := "balanced"
	if morningVisits > afternoonVisits && morningVisits > eveningVisits && morningVisits > nightVisits {
		timePatternType = "morning_person"
	} else if afternoonVisits > morningVisits && afternoonVisits > eveningVisits && afternoonVisits > nightVisits {
		timePatternType = "afternoon_person"
	} else if eveningVisits > morningVisits && eveningVisits > afternoonVisits && eveningVisits > nightVisits {
		timePatternType = "evening_person"
	} else if nightVisits > morningVisits && nightVisits > afternoonVisits && nightVisits > eveningVisits {
		timePatternType = "night_owl"
	}

	patterns := map[string]interface{}{
		"total_visits":        totalVisits,
		"peak_hour":           peakHour,
		"peak_hour_visits":    maxHourlyVisits,
		"hourly_distribution": hourlyVisits,
		"time_periods": map[string]interface{}{
			"morning": map[string]interface{}{
				"visits":     morningVisits,
				"percentage": math.Round(float64(morningVisits)/float64(totalVisits)*10000) / 100,
			},
			"afternoon": map[string]interface{}{
				"visits":     afternoonVisits,
				"percentage": math.Round(float64(afternoonVisits)/float64(totalVisits)*10000) / 100,
			},
			"evening": map[string]interface{}{
				"visits":     eveningVisits,
				"percentage": math.Round(float64(eveningVisits)/float64(totalVisits)*10000) / 100,
			},
			"night": map[string]interface{}{
				"visits":     nightVisits,
				"percentage": math.Round(float64(nightVisits)/float64(totalVisits)*10000) / 100,
			},
		},
		"time_pattern_type": timePatternType,
	}

	log.Printf("时间模式分析完成: 高峰时段%d点, 模式类型: %s", peakHour, timePatternType)

	return patterns
}

// analyzeDomainPatterns 分析域名分布模式
func (pa *PatternAnalyzer) analyzeDomainPatterns() map[string]interface{} {
	log.Printf("分析域名分布模式")

	domainStats := make(map[string]*DomainStats)
	totalVisits := 0

	// 统计域名信息
	for _, feature := range pa.features {
		domain := feature.Domain
		if domain == "" {
			domain = "unknown"
		}

		if _, exists := domainStats[domain]; !exists {
			domainStats[domain] = &DomainStats{
				Domain:     domain,
				URLCount:   0,
				VisitCount: 0,
				Categories: make(map[string]int),
			}
		}

		stats := domainStats[domain]
		stats.URLCount++
		stats.VisitCount += feature.VisitCount
		stats.Categories[feature.Category]++
		totalVisits += feature.VisitCount
	}

	// 转换为切片并排序
	domainList := make([]*DomainStats, 0, len(domainStats))
	for _, stats := range domainStats {
		domainList = append(domainList, stats)
	}

	// 按访问次数排序
	sort.Slice(domainList, func(i, j int) bool {
		return domainList[i].VisitCount > domainList[j].VisitCount
	})

	// 计算集中度指标
	top10Domains := 0
	top10Visits := 0
	for i, stats := range domainList {
		if i < 10 {
			top10Domains++
			top10Visits += stats.VisitCount
		}
	}

	// 计算基尼系数 (简化版)
	giniCoefficient := pa.calculateGiniCoefficient(domainList)

	patterns := map[string]interface{}{
		"total_domains": len(domainStats),
		"total_visits":  totalVisits,
		"concentration": map[string]interface{}{
			"top_10_domains":    top10Domains,
			"top_10_visits":     top10Visits,
			"top_10_percentage": math.Round(float64(top10Visits)/float64(totalVisits)*10000) / 100,
			"gini_coefficient":  math.Round(giniCoefficient*10000) / 100,
		},
		"top_domains":      pa.getTopDomains(domainList, 10),
		"domain_diversity": pa.calculateDiversity(domainStats),
	}

	log.Printf("域名模式分析完成: %d个域名, 前10个占%.2f%%访问",
		len(domainStats), math.Round(float64(top10Visits)/float64(totalVisits)*10000)/100)

	return patterns
}

// analyzeContentPatterns 分析内容分类模式
func (pa *PatternAnalyzer) analyzeContentPatterns() map[string]interface{} {
	log.Printf("分析内容分类模式")

	categoryStats := make(map[string]*CategoryStats)
	totalVisits := 0

	// 统计分类信息
	for _, feature := range pa.features {
		category := feature.Category
		if category == "" {
			category = "未分类"
		}

		if _, exists := categoryStats[category]; !exists {
			categoryStats[category] = &CategoryStats{
				Category:   category,
				URLCount:   0,
				VisitCount: 0,
				Domains:    make(map[string]int),
			}
		}

		stats := categoryStats[category]
		stats.URLCount++
		stats.VisitCount += feature.VisitCount
		stats.Domains[feature.Domain]++
		totalVisits += feature.VisitCount
	}

	// 转换为切片并排序
	categoryList := make([]*CategoryStats, 0, len(categoryStats))
	for _, stats := range categoryStats {
		categoryList = append(categoryList, stats)
	}

	// 按访问次数排序
	sort.Slice(categoryList, func(i, j int) bool {
		return categoryList[i].VisitCount > categoryList[j].VisitCount
	})

	// 计算兴趣多样性
	interestDiversity := pa.calculateInterestDiversity(categoryList)

	patterns := map[string]interface{}{
		"total_categories":      len(categoryStats),
		"total_visits":          totalVisits,
		"interest_diversity":    interestDiversity,
		"category_distribution": pa.getCategoryDistribution(categoryList),
		"top_categories":        pa.getTopCategories(categoryList, 10),
	}

	log.Printf("内容模式分析完成: %d个分类, 多样性指数: %.2f",
		len(categoryStats), interestDiversity)

	return patterns
}

// analyzeBehaviorPatterns 分析用户行为模式
func (pa *PatternAnalyzer) analyzeBehaviorPatterns() map[string]interface{} {
	log.Printf("分析用户行为模式")

	// 分析访问深度
	shallowVisits := 0 // 访问次数 <= 5
	mediumVisits := 0  // 访问次数 6-20
	deepVisits := 0    // 访问次数 > 20

	// 分析URL类型
	homepageVisits := 0
	subpageVisits := 0
	searchVisits := 0

	// 分析访问模式
	singleVisitURLs := 0
	recurringURLs := 0

	totalVisits := 0
	for _, feature := range pa.features {
		visits := feature.VisitCount
		totalVisits += visits

		// 访问深度分析
		if visits <= 5 {
			shallowVisits += visits
		} else if visits <= 20 {
			mediumVisits += visits
		} else {
			deepVisits += visits
		}

		// URL类型分析
		url := strings.ToLower(feature.URL)
		if strings.HasSuffix(url, "/") || strings.Count(url, "/") <= 3 {
			homepageVisits += visits
		} else {
			subpageVisits += visits
		}

		if strings.Contains(url, "search") || strings.Contains(url, "query") {
			searchVisits += visits
		}

		// 访问模式分析
		if visits == 1 {
			singleVisitURLs++
		} else {
			recurringURLs++
		}
	}

	// 计算行为类型
	behaviorType := "balanced"
	if deepVisits > shallowVisits && deepVisits > mediumVisits {
		behaviorType = "deep_explorer"
	} else if shallowVisits > deepVisits && shallowVisits > mediumVisits {
		behaviorType = "shallow_browser"
	} else if singleVisitURLs > recurringURLs*2 {
		behaviorType = "one_time_visitor"
	} else if recurringURLs > singleVisitURLs*2 {
		behaviorType = "loyal_user"
	}

	patterns := map[string]interface{}{
		"total_visits": totalVisits,
		"visit_depth": map[string]interface{}{
			"shallow": map[string]interface{}{
				"visits":     shallowVisits,
				"percentage": math.Round(float64(shallowVisits)/float64(totalVisits)*10000) / 100,
			},
			"medium": map[string]interface{}{
				"visits":     mediumVisits,
				"percentage": math.Round(float64(mediumVisits)/float64(totalVisits)*10000) / 100,
			},
			"deep": map[string]interface{}{
				"visits":     deepVisits,
				"percentage": math.Round(float64(deepVisits)/float64(totalVisits)*10000) / 100,
			},
		},
		"url_types": map[string]interface{}{
			"homepage_visits": homepageVisits,
			"subpage_visits":  subpageVisits,
			"search_visits":   searchVisits,
		},
		"visit_patterns": map[string]interface{}{
			"single_visit_urls": singleVisitURLs,
			"recurring_urls":    recurringURLs,
			"loyalty_ratio":     math.Round(float64(recurringURLs)/float64(len(pa.features))*10000) / 100,
		},
		"behavior_type": behaviorType,
	}

	log.Printf("行为模式分析完成: 类型: %s, 忠诚度: %.2f%%",
		behaviorType, math.Round(float64(recurringURLs)/float64(len(pa.features))*10000)/100)

	return patterns
}

// analyzeInterestPatterns 分析兴趣偏好模式
func (pa *PatternAnalyzer) analyzeInterestPatterns() map[string]interface{} {
	log.Printf("分析兴趣偏好模式")

	// 关键词分析
	keywordCount := make(map[string]int)
	domainKeywords := make(map[string]map[string]int)

	for _, feature := range pa.features {
		// 分析标题关键词
		title := strings.ToLower(feature.Title)
		words := strings.Fields(title)
		for _, word := range words {
			if len(word) > 2 {
				keywordCount[word]++
			}
		}

		// 分析域名关键词
		domain := strings.ToLower(feature.Domain)
		if domainKeywords[domain] == nil {
			domainKeywords[domain] = make(map[string]int)
		}
		for _, word := range words {
			if len(word) > 2 {
				domainKeywords[domain][word]++
			}
		}
	}

	// 获取热门关键词
	topKeywords := pa.getTopKeywords(keywordCount, 20)

	// 分析兴趣领域
	interestAreas := pa.identifyInterestAreas(keywordCount)

	// 计算兴趣集中度
	interestConcentration := pa.calculateInterestConcentration(keywordCount)

	patterns := map[string]interface{}{
		"total_keywords":          len(keywordCount),
		"top_keywords":            topKeywords,
		"interest_areas":          interestAreas,
		"interest_concentration":  interestConcentration,
		"domain_keyword_analysis": pa.analyzeDomainKeywords(domainKeywords),
	}

	log.Printf("兴趣模式分析完成: %d个关键词, %d个兴趣领域",
		len(keywordCount), len(interestAreas))

	return patterns
}

// 辅助结构体
type DomainStats struct {
	Domain     string
	URLCount   int
	VisitCount int
	Categories map[string]int
}

type CategoryStats struct {
	Category   string
	URLCount   int
	VisitCount int
	Domains    map[string]int
}

// 辅助方法
func (pa *PatternAnalyzer) calculateAverage(values []int) float64 {
	if len(values) == 0 {
		return 0
	}
	sum := 0
	for _, v := range values {
		sum += v
	}
	return float64(sum) / float64(len(values))
}

func (pa *PatternAnalyzer) calculateMedian(values []int) int {
	if len(values) == 0 {
		return 0
	}
	n := len(values)
	if n%2 == 0 {
		return (values[n/2-1] + values[n/2]) / 2
	}
	return values[n/2]
}

func (pa *PatternAnalyzer) calculatePercentile(values []int, percentile int) int {
	if len(values) == 0 {
		return 0
	}
	index := int(float64(len(values)) * float64(percentile) / 100.0)
	if index >= len(values) {
		index = len(values) - 1
	}
	return values[index]
}

func (pa *PatternAnalyzer) getTopURLs(features []models.URLFeature, count int) []map[string]interface{} {
	result := make([]map[string]interface{}, 0, count)
	for i, feature := range features {
		if i >= count {
			break
		}
		result = append(result, map[string]interface{}{
			"url":      feature.URL,
			"title":    feature.Title,
			"visits":   feature.VisitCount,
			"category": feature.Category,
		})
	}
	return result
}

func (pa *PatternAnalyzer) getTopDomains(domains []*DomainStats, count int) []map[string]interface{} {
	result := make([]map[string]interface{}, 0, count)
	for i, stats := range domains {
		if i >= count {
			break
		}
		result = append(result, map[string]interface{}{
			"domain":      stats.Domain,
			"url_count":   stats.URLCount,
			"visit_count": stats.VisitCount,
			"percentage":  math.Round(float64(stats.VisitCount)/float64(pa.getTotalVisits())*10000) / 100,
		})
	}
	return result
}

func (pa *PatternAnalyzer) getTotalVisits() int {
	total := 0
	for _, feature := range pa.features {
		total += feature.VisitCount
	}
	return total
}

func (pa *PatternAnalyzer) calculateGiniCoefficient(domains []*DomainStats) float64 {
	if len(domains) == 0 {
		return 0
	}

	// 简化的基尼系数计算
	n := len(domains)
	totalVisits := 0
	for _, stats := range domains {
		totalVisits += stats.VisitCount
	}

	if totalVisits == 0 {
		return 0
	}

	// 按访问次数排序
	sort.Slice(domains, func(i, j int) bool {
		return domains[i].VisitCount < domains[j].VisitCount
	})

	gini := 0.0
	for i, stats := range domains {
		gini += float64(2*i+1) * float64(stats.VisitCount)
	}

	return gini/float64(n*totalVisits) - float64(n+1)/float64(n)
}

func (pa *PatternAnalyzer) calculateDiversity(domains map[string]*DomainStats) float64 {
	if len(domains) == 0 {
		return 0
	}

	// 计算香农多样性指数
	totalVisits := 0
	for _, stats := range domains {
		totalVisits += stats.VisitCount
	}

	if totalVisits == 0 {
		return 0
	}

	diversity := 0.0
	for _, stats := range domains {
		p := float64(stats.VisitCount) / float64(totalVisits)
		if p > 0 {
			diversity -= p * math.Log2(p)
		}
	}

	return math.Round(diversity*100) / 100
}

func (pa *PatternAnalyzer) getCategoryDistribution(categories []*CategoryStats) []map[string]interface{} {
	result := make([]map[string]interface{}, 0, len(categories))
	totalVisits := pa.getTotalVisits()

	for _, stats := range categories {
		result = append(result, map[string]interface{}{
			"category":    stats.Category,
			"url_count":   stats.URLCount,
			"visit_count": stats.VisitCount,
			"percentage":  math.Round(float64(stats.VisitCount)/float64(totalVisits)*10000) / 100,
		})
	}
	return result
}

func (pa *PatternAnalyzer) getTopCategories(categories []*CategoryStats, count int) []map[string]interface{} {
	result := make([]map[string]interface{}, 0, count)
	for i, stats := range categories {
		if i >= count {
			break
		}
		result = append(result, map[string]interface{}{
			"category":    stats.Category,
			"url_count":   stats.URLCount,
			"visit_count": stats.VisitCount,
		})
	}
	return result
}

func (pa *PatternAnalyzer) calculateInterestDiversity(categories []*CategoryStats) float64 {
	if len(categories) == 0 {
		return 0
	}

	totalVisits := 0
	for _, stats := range categories {
		totalVisits += stats.VisitCount
	}

	if totalVisits == 0 {
		return 0
	}

	diversity := 0.0
	for _, stats := range categories {
		p := float64(stats.VisitCount) / float64(totalVisits)
		if p > 0 {
			diversity -= p * math.Log2(p)
		}
	}

	return math.Round(diversity*100) / 100
}

func (pa *PatternAnalyzer) getTopKeywords(keywords map[string]int, count int) []map[string]interface{} {
	// 转换为切片并排序
	keywordList := make([]struct {
		word  string
		count int
	}, 0, len(keywords))

	for word, count := range keywords {
		keywordList = append(keywordList, struct {
			word  string
			count int
		}{word, count})
	}

	sort.Slice(keywordList, func(i, j int) bool {
		return keywordList[i].count > keywordList[j].count
	})

	result := make([]map[string]interface{}, 0, count)
	for i, item := range keywordList {
		if i >= count {
			break
		}
		result = append(result, map[string]interface{}{
			"keyword": item.word,
			"count":   item.count,
		})
	}
	return result
}

func (pa *PatternAnalyzer) identifyInterestAreas(keywords map[string]int) []string {
	// 简化的兴趣领域识别
	interestAreas := []string{}

	// 技术相关
	techKeywords := []string{"code", "programming", "development", "github", "stackoverflow", "api", "software"}
	if pa.hasKeywords(keywords, techKeywords) {
		interestAreas = append(interestAreas, "技术开发")
	}

	// 新闻相关
	newsKeywords := []string{"news", "article", "report", "breaking", "update"}
	if pa.hasKeywords(keywords, newsKeywords) {
		interestAreas = append(interestAreas, "新闻资讯")
	}

	// 娱乐相关
	entertainmentKeywords := []string{"video", "movie", "music", "game", "entertainment"}
	if pa.hasKeywords(keywords, entertainmentKeywords) {
		interestAreas = append(interestAreas, "娱乐休闲")
	}

	// 学习相关
	learningKeywords := []string{"tutorial", "learn", "course", "education", "study"}
	if pa.hasKeywords(keywords, learningKeywords) {
		interestAreas = append(interestAreas, "学习教育")
	}

	// 购物相关
	shoppingKeywords := []string{"shop", "buy", "product", "price", "deal"}
	if pa.hasKeywords(keywords, shoppingKeywords) {
		interestAreas = append(interestAreas, "购物消费")
	}

	return interestAreas
}

func (pa *PatternAnalyzer) hasKeywords(keywords map[string]int, targetKeywords []string) bool {
	for _, keyword := range targetKeywords {
		if keywords[keyword] > 0 {
			return true
		}
	}
	return false
}

func (pa *PatternAnalyzer) calculateInterestConcentration(keywords map[string]int) float64 {
	if len(keywords) == 0 {
		return 0
	}

	totalCount := 0
	for _, count := range keywords {
		totalCount += count
	}

	if totalCount == 0 {
		return 0
	}

	// 计算前10%关键词的占比
	keywordList := make([]int, 0, len(keywords))
	for _, count := range keywords {
		keywordList = append(keywordList, count)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(keywordList)))

	top10Count := len(keywordList) / 10
	if top10Count == 0 {
		top10Count = 1
	}

	top10Total := 0
	for i := 0; i < top10Count && i < len(keywordList); i++ {
		top10Total += keywordList[i]
	}

	return math.Round(float64(top10Total)/float64(totalCount)*10000) / 100
}

func (pa *PatternAnalyzer) analyzeDomainKeywords(domainKeywords map[string]map[string]int) map[string]interface{} {
	result := make(map[string]interface{})

	for domain, keywords := range domainKeywords {
		if len(keywords) == 0 {
			continue
		}

		// 获取该域名的热门关键词
		keywordList := make([]struct {
			word  string
			count int
		}, 0, len(keywords))

		for word, count := range keywords {
			keywordList = append(keywordList, struct {
				word  string
				count int
			}{word, count})
		}

		sort.Slice(keywordList, func(i, j int) bool {
			return keywordList[i].count > keywordList[j].count
		})

		// 只保留前5个关键词
		topKeywords := make([]string, 0, 5)
		for i, item := range keywordList {
			if i >= 5 {
				break
			}
			topKeywords = append(topKeywords, item.word)
		}

		result[domain] = topKeywords
	}

	return result
}
